<?php


namespace App\Extensions\Column;

use Encore\Admin\Grid\Column\CheckFilter;
use Encore\Admin\Grid\Model;

class CheckRelationFilter extends CheckFilter
{
    /**
     * @var array
     */
    protected $options;
    protected $relation;
    /**
     * @var
     */
    protected $column;

    /**
     * CheckRelationFilter constructor.
     * @param array $options
     * @param $relation
     * @param $column
     */
    public function __construct(array $options, $relation, $column='')
    {
        $this->relation = $relation;
        $this->column = $column;
        parent::__construct($options);
    }

    /**
     * 修正Grid 关联无法获取request值 如；
     * @return array|mixed|string|string[]
     */
    public function getColumnName()
    {
        return str_replace('.', '_', $this->parent->getName());
    }
    /**
     * Add a binding to the query.
     * 自定义 关联
     * @param array $value
     * @param Model $model
     */
    public function addBinding($value, Model $model)
    {
        $value = $this->getFilterValue();
        if (empty($value)) {
            return;
        }
        if ($this->relation instanceof \Closure) {
            $callback = $this->relation->bindTo($model);
            call_user_func_array($callback, [$model,$value]);
        } else {
            $model->whereHas($this->relation,function($query)use($value){
                return $query->whereIn($this->column,$value);
            });
        }
    }
}
